#include <signal.h>

#include <chrono>
#include <cstring>
#include <thread>

#include "src/base/fio66_logger.h"
#include "src/base/utils.h"
#include "src/net/event_loop.h"
#include "src/server/blog_server.h"

constinit static sigset_t wait_mask;

bool InitQuitSignal() {
  memset(&wait_mask, 0, sizeof(wait_mask));
  signal(SIGKILL, SIG_IGN);
  sigemptyset(&wait_mask);
  sigaddset(&wait_mask, SIGINT);
  sigaddset(&wait_mask, SIGQUIT);
  sigaddset(&wait_mask, SIGTERM);
  pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
  return true;
}

bool WaitForQuit() {
  timespec time_spec;
  siginfo_t sig;
  ZeroMemory(time_spec);
  ZeroMemory(sig);
  time_spec.tv_sec = 0;
  time_spec.tv_nsec = 0;
  auto signal = sigtimedwait(&wait_mask, &sig, &time_spec);
  switch (signal) {
    case SIGINT:
    case SIGQUIT:
    case SIGTERM:
      LOGI << "Get quit signal:" << signal;
      return false;
    default:
      break;
  }
  return true;
}

std::optional<fio66::BlogServerConfig> ParseConfigFile(std::string_view file_path) { return fio66::utils::GetJSONObjFromFile<fio66::BlogServerConfig>(file_path, "blog_server"); }

int main() {
  fio66::Fio66Logger::GetInstance()->Init("http_server");
  LOGI << "Run http server!";

  auto config = ParseConfigFile("./blog_server_config.json");
  if (config) {
    fio66::net::EventLoop loop;
    fio66::BlogServer server(config.value(), &loop); 
    server.Start();
    loop.Loop();
  }
  LOGI << "Http server quit!";
  fio66::Fio66Logger::GetInstance()->Uninit();
  return 0;
}